﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Configuration;
using System.Linq;

public partial class adm_vlg_yeuCauThanhToanSuccess : System.Web.UI.Page
{
    VLGDataContext _db8 = new VLGDataContext();
    YeuCauChuyenKhoan _object = null;
    String sKey, sValue, fname, lname, mc_gross, itemName, Pmtcurrency, itemNumber, payer_email, receiver_email, txn_id;
    String item_name1;
    String authToken, txToken, query;
    String strResponse;
    string url = "";
    protected void Page_Load(object sender, EventArgs e)
    { /*
  * set this to the value of the PDT token for your account
  * see http://paypaltech.com/PDTGen/PDTtokenhelp.htm for help with this
 */
        if (String.Compare(ConfigurationManager.AppSettings["UseSandbox"].ToString(), "true", false) == 0)
        {
            url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
        }
        else
        {
            url = "https://www.paypal.com/cgi-bin/webscr";
        }
        //id token lấy trong thông tin tài khoản paypal--> profile --> web reference
        authToken = "q9yWtGCLzZxNLcB_on1Ao9GhozolbYtE19jEQBcAd2jp-v70RA6IA-yQcY0";
        //read in txn token from querystring
        txToken = Request.QueryString.Get("tx");


        //:::sanity check
        //Response.Write(txToken);

        query = "cmd=_notify-synch&tx=" + txToken + "&at=" + authToken;


        // Create the request back
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        // Set values for the request back
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = query.Length;

        // Write the request back IPN strings
        StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
        stOut.Write(query);
        stOut.Close();

        // Do the request to PayPal and get the response
        StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
        strResponse = stIn.ReadToEnd();
        stIn.Close();

        //:::sanity check:::
        //Response.Write("PDT returned: " + strResponse + "<p></p>");


        // If response was SUCCESS, parse response string and
        //output details
        if (strResponse.Substring(0, 7) == "SUCCESS")
        {
            //split response into string array using whitespace
            //as delimiter
            String[] StringArray = strResponse.Split();


            // NOTE:
            /*
            * loop is set to start at 1 rather than 0 because first
            string in array will be single word SUCCESS or FAIL
            and there is no splitting of this...so we will skip the
            first string and go to the next.
            */

            // use split to split array we already have
            // using "=" as delimiter
            int i;
            for (i = 1; i < StringArray.Length - 1; i++)
            {
                String[] StringArray1 = StringArray[i].Split('=');

                sKey = StringArray1[0];
                sValue = StringArray1[1];


                // set string vars to hold variable names using a switch
                switch (sKey)
                {
                    case "first_name":
                        fname = sValue;
                        break;

                    case "last_name":
                        lname = sValue;
                        break;

                    case "mc_gross":
                        mc_gross = sValue;
                        break;

                    case "item_name":
                        itemName = sValue;
                        break;

                    //for shopping cart payments the
                    //item_name vars are numbered to reflect
                    //a multi-item purchase.
                    case "item_name1":
                        item_name1 = sValue;
                        break;

                    case "mc_currency":
                        Pmtcurrency = sValue;
                        break;
                    case "item_number":
                        itemNumber = sValue;
                        break;
                    case "payer_email":
                        payer_email = sValue;
                        break;
                    case "receiver_email":
                        receiver_email = sValue;
                        break;
                    case "txn_id":
                        txn_id = sValue;
                        break;
                }
            }
            try
            {

                _object = _db8.YeuCauChuyenKhoans.Single(x => x.idYCCK == Convert.ToInt32(itemNumber));
                _object.status = true;
                var acc = _db8.VLGAccounts.Single(c => c.idAcc == _object.idAcc);
                acc.soTien = acc.soTien - _object.soTien;
                //thong tin chuyen khoan
                var chuyenKhoan = new ChuyenKhoan();
                chuyenKhoan.idAcc = _object.idAcc;
                chuyenKhoan.soTien = _object.soTien;
                chuyenKhoan.ngay = DateTime.Now;
                //0 rút, 1 gửi
                chuyenKhoan.loai = 0;
                chuyenKhoan.idYCCK = _object.idYCCK;
                _db8.ChuyenKhoans.InsertOnSubmit(chuyenKhoan);
                _db8.SubmitChanges();
                //chuyen khoan paypal
                //var chuyenKhoanLog = new ChuyenKhoanLog();
                //chuyenKhoanLog.ngay = DateTime.Now;
                //chuyenKhoanLog.emailNhan = Server.UrlDecode(receiver_email);
                //chuyenKhoanLog.emailGui = Server.UrlDecode(payer_email);
                //chuyenKhoanLog.soTien = Convert.ToDecimal(mc_gross);
                //chuyenKhoanLog.idCK = chuyenKhoan.idCH;
                //chuyenKhoanLog.noiDung = "";
                ////0 rut, 1 gửi
                //chuyenKhoanLog.loai = 0;
                //_db8.ChuyenKhoanLogs.InsertOnSubmit(chuyenKhoanLog);
                //_db8.SubmitChanges();
                FillData();

            }
            catch
            {
                ltrMessage.Text = "Thanh toán thất bại";
            }


        }

        else if (strResponse.Substring(0, 4) == "FAIL")
        {
            // if response is FAIL, print it to screen
            Response.Write(strResponse);
            ltrMessage.Text = "Thanh toán thất bại";
        }

        else
        {
            // some unexpected response??? -  log it
            // for investigation later.

        }



    }
    public void FillData()
    {
        if (_object != null)
        {
            hdId.Value = _object.idYCCK.ToString();
            lblTaiKhoan.Text = _object.VLGAccount.UsernameE;
            lblSoTien.Text = _object.soTien.ToString();
            ltrMessage.Text = "Thanh toán thành công";
        }
    }
    protected void butt_save_Click(object sender, EventArgs e)
    {
        _object = _db8.YeuCauChuyenKhoans.Single(x => x.idYCCK == Convert.ToInt32(hdId.Value));
        PaypalProcess _paypalProcess = new PaypalProcess();
        string returnURL = "http://localhost:23910/ViecLamGap/Default5.aspx";
        string returnCancelURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
        string server = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
        string business = "nhathn_1342581970_biz@gmail.com";
        string itemName = _object.idYCCK.ToString();
        int itemNumber = _object.idYCCK;
        int amount = (int)_object.soTien;
        Response.Redirect(_paypalProcess.GetPaypalProcess(returnURL, returnCancelURL, server, business, itemName, itemNumber, amount));
    }
}